import java.util.Date;
import java.util.concurrent.*;

/**
 * @projectName: java-daily-questions
 * @package: PACKAGE_NAME
 * @className: ThreadPoolDemo
 * @author: ZM
 * @description: 线程池 - demo
 * @date: 2021/8/21 17:46
 * @version: 1.0
 */
public class ThreadPoolDemo {

    static class MyRunnable implements Runnable {

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "->" + new Date());
        }
    }

    public static void main(String[] args) {
        // 单个线程的线程池
        ExecutorService singleThread = Executors.newSingleThreadExecutor();
        // 固定数量线程池
        ExecutorService fixedThread = Executors.newFixedThreadPool(11);
        // 缓存线程池
        ExecutorService cachedThread = Executors.newCachedThreadPool();
        // 定时线程池
        ScheduledExecutorService scheduledThread = Executors.newScheduledThreadPool(1);

        singleThread.submit(()-> {
            System.out.println("single thread task run!");
        });
        singleThread.shutdown();

        fixedThread.submit(()-> {
            System.out.println("fixed thread task run!");
        });
        fixedThread.shutdown();

        cachedThread.submit(()-> {
            System.out.println("cached thread task run!");
        });
        cachedThread.shutdown();

        // 任务执行时间（8s）小于间隔时间(10s)
        scheduledThread.scheduleAtFixedRate(() -> {
            System.out.println("Start: scheduleAtFixedRate:    " + new Date());
            try {
                Thread.sleep(8000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("End  : scheduleAtFixedRate:    " + new Date());
        }, 0, 10 , TimeUnit.SECONDS);

        scheduledThread.scheduleAtFixedRate(() -> {
            System.out.println("Start: scheduleAtFixedRate:    " + new Date());
            try {
                Thread.sleep(12000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("End  : scheduleAtFixedRate:    " + new Date());
        }, 0, 10 , TimeUnit.SECONDS);

        ThreadFactory factory = r -> new Thread(r, "myThread-" + r.hashCode());
        ThreadPoolExecutor myPool = new ThreadPoolExecutor(5, 10, 60, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1024), factory, new ThreadPoolExecutor.AbortPolicy());
        myPool.submit(() -> {
            System.out.println("the Thread pool task run!");
        });
    }

}
